package cn.edu.lzzy.mypractices.web.chapter;

import cn.edu.lzzy.mypractices.constant.ApiConstant;
import cn.edu.lzzy.mypractices.constant.Messages;
import cn.edu.lzzy.mypractices.entity.Option;
import cn.edu.lzzy.mypractices.entity.Question;
import cn.edu.lzzy.mypractices.entity.Result;
import cn.edu.lzzy.mypractices.entity.User;
import cn.edu.lzzy.mypractices.repository.OptionRepository;
import cn.edu.lzzy.mypractices.repository.QuestionRepository;
import cn.edu.lzzy.mypractices.repository.ResultRepository;
import cn.edu.lzzy.mypractices.repository.UserRepository;
import cn.edu.lzzy.mypractices.service.ResultService;
import cn.edu.lzzy.mypractices.web.model.ApiResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Api(tags = "题目对错查询相关业务")
@CrossOrigin
@RestController
@RequestMapping(ApiConstant.ROUTE_RESULT_ROOT)
public class ResultApiController {

    private final ResultService resultService;
    private final UserRepository userRepository;
    private final QuestionRepository questionRepository;
    private final OptionRepository optionRepository;
    private final ResultRepository resultRepository;

    public ResultApiController(ResultService resultService, // 我已经不想做鉴权了 爱怎样怎样吧 已经很累了
                               UserRepository userRepository,
                               QuestionRepository questionRepository,
                               OptionRepository optionRepository,
                               ResultRepository resultRepository) {
        this.resultService = resultService;
        this.userRepository = userRepository;
        this.questionRepository = questionRepository;
        this.optionRepository = optionRepository;
        this.resultRepository = resultRepository;
    }

    @ApiOperation("查询正确答题者")
    @GetMapping(ApiConstant.ROUTE_RESULT_QUESTION)
    public ApiResult findCorrectAnswerUsers(@RequestParam UUID questionId) {
        List<ApiResult.VmUser> userList = new ArrayList<>(); // 性能 == 不要钱
        resultService.getAllAnsweredRightUsers(questionId).forEach(o -> userList.add(ApiResult.VmUser.create(o)));
        return new ApiResult(true, userList.size() + "", userList);
    }

    @ApiOperation("查询章节成绩")
    @GetMapping(ApiConstant.ROUTE_RESULT_CHAPTER)
    public ApiResult checkScore(@RequestParam UUID userId, @RequestParam UUID chapterId) {
        int score = resultService.getScore(userId, chapterId);
        return new ApiResult(true, score == -1 ? "业务错误" : Messages.SUCCESS.toString(), score);
    }

    @ApiOperation("提交答题")
    @PostMapping(ApiConstant.ROUTE_RESULT_POST)
    public ApiResult postAnswer(@RequestParam UUID userId, @RequestParam UUID questionId, @RequestBody JSONArray options) {
        if (resultRepository.findByStudentIdAndQuestionId(userId, questionId) != null) {
            return new ApiResult(false, "你已经答过该题目了!", null);
        }

        Result r = new Result();
        List<UUID> arr = new ArrayList<>();

        options.toJavaList(String.class).forEach(s -> arr.add(UUID.fromString(s)));

        if (userId != null && questionId != null && arr.size() > 0) {
            User u = userRepository.findById(userId).orElse(null);
            if (u != null) {
                Question q = questionRepository.findById(questionId).orElse(null);
                if (q != null) {
                    r.setStudent(u);
                    r.setQuestion(q);
                    List<Option> opts = optionRepository.findAllById(arr);
                    if (opts.size() > 0) {
                        r.setOptions(opts);
                        r.setCommitTime(new Date());
                        Result saved = resultService.answerQuestion(r);
                        if (saved != null) {
                            return new ApiResult(true, Messages.SUCCESS.toString(), null);
                        }
                    }
                }
            }
        }

        return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
    }

    @ApiOperation("查询题目答题状态")
    @GetMapping(ApiConstant.ROUTE_RESULT_ONE)
    public ApiResult checkQuestionStatus(@RequestParam UUID userId, @RequestParam UUID questionId) {
        int status = resultService.getAnswerResult(userId, questionId);
        JSONObject obj = new JSONObject();
        obj.put("type", status);
        obj.put("type_text", getAnswerType(status));
        return new ApiResult(true, Messages.SUCCESS.toString(), obj);
    }

    public String getAnswerType(int i) {
        switch (i) {
            case Result.CORRECT:
                return "正确";

            case Result.LES_SELECTION:
                return "漏选";

            case Result.OVR_SELECTION:
                return "多选";

            case Result.MIS_SELECTION:
                return "错误";

            case Result.NOT_DONE:
                return "未完成";

            default:
                return "未知";
        }
    }
}
